var _root_xmouse = 0;
var _root_ymouse = 0;

var GLOBAL_plugin;
var GLOBAL_MouseMoveTimer;
var GLOBAL_screen;
var GLOBAL_time = 4000;

function globalMouseTest(sender, args) {
    var pt = args.getPosition(null);
    _root_xmouse = pt.x
    _root_ymouse = pt.y	
    
    if(GLOBAL_plugin.content.fullScreen) {
        clearTimeout(GLOBAL_MouseMoveTimer);
        GLOBAL_MouseMoveTimer = setTimeout(HideControlsTimer, GLOBAL_time);
        ToggleControlsSelector(true);
    } else {
        clearTimeout(GLOBAL_MouseMoveTimer);
    }
}

function HideControlsTimer() {
    if(GLOBAL_plugin.content.fullScreen) {
        ToggleControlsSelector(false);
    }
}

function ToggleControlsSelector(flag) {
    if(GLOBAL_plugin.content.fullScreen){
        var bgCont = GLOBAL_plugin.content.findName("BtmControls");
        if(flag) {
            var ctrlsIn = GLOBAL_plugin.content.findName("btmControlsIn");
            if (bgCont.Opacity == 0) {
                ctrlsIn.begin();    
            }
        } else if (!flag) {
            var ctrlsOut = GLOBAL_plugin.content.findName("btmControlsOut");
            
            if (bgCont.Opacity == 1 && _root_ymouse <  GLOBAL_plugin.content.actualHeight - 10) { //
                ctrlsOut.begin();
            }    
        }
 
    }
}

function PlayerControls_MouseEnter(sender, Args){
    if(GLOBAL_plugin.content.fullScreen) {
        clearTimeout(GLOBAL_MouseMoveTimer);
    }
}

function PlayerControls_MouseLeave(sender, Args) {
    if(GLOBAL_plugin.content.fullScreen){
        clearTimeout(GLOBAL_MouseMoveTimer);
        GLOBAL_MouseMoveTimer = setTimeout(HideControlsTimer, GLOBAL_time);
    }
}

function NRKPlayer(parentId, url, volume, autoStart, showTitleBar, showControlBar) { //, volume, aspectRatio, autoStart, showTitleBar, showContralBar
    this.mediaURL = url;
    
    if (volume != null) {
        this.playerVolume = volume;
    } else {
        this.playerVolume = 0.5;
    }
        
    if (autoStart != null) {
        this.playerAutoStart = autoStart;
    } else {
        this.playerAutoStart = true;
    }
    
    if (showTitleBar != null) {
        this.playerTitleBar = showTitleBar;
    } else {
        this.playerTitleBar = showTitleBar;
    }
    
    if (showControlBar != null) {
        this.playerControlBar = showControlBar;
    } else {
        this.playerControlBar = showControlBar;
    }
    
    this.playerWidth = "512";
    this.playerHeight = "324";
    
    this._hostname = EePlayer.Player._getUniqueName("xamlHost");
    Silverlight.createObjectEx( {   source: '/static/player_16.9_internal.xaml', 
                                        parentElement: $get(parentId || "SilverlightPlayer"), 
                                        id:this._hostname, 
                                       
                                        properties:{ width:this.playerWidth, height:this.playerHeight, version:'1.0', background:'Black', isWindowless:'false' }, 
                                        events:{ onError:null, onLoad:Function.createDelegate(this, this._handleLoad)
                                         } } );
          
}

NRKPlayer.prototype = {
	
    _handleError: function(control, context, rootElement)
	{
	alert('error!');
	},
    
    _handleLoad: function(control, context, rootElement) {
        this.plugin = control;
              
        this._player = $create(   ExtendedPlayer.Player, 
                                  { // properties
                                    autoPlay    : this.playerAutoStart, 
                                    volume      : this.playerVolume,
                                    muted       : false
                                  }, 
                                  { // event handlers
                                    mediaOpened: Function.createDelegate(this, this._onMediaOpened),
                                    mediaEnded: Function.createDelegate(this, this._onMediaEnded),
                                    mediaFailed: Function.createDelegate(this, this._onMediaFailed),
                                    markerReached: Function.createDelegate(this, this._onMarkerReached),
                                    volumeChanged: Function.createDelegate(this, this._onVolumeChanged),
                                    stateChanged: Function.createDelegate(this, this._onStateChanged),
                                    chapterStarted: Function.createDelegate(this, this._onChapterStarted)
                                    //timeSliderChanged: Function.createDelegate(this, this.onTimeSliderChanged)

                                  },
                                  null, $get(this._hostname)  ); 
        
        GLOBAL_plugin = control;
           
        this.MediaPlayer = control.content.findName("VideoWindow");
        this._currentMediainfo = -1;
        this.currentChapter = 0;
        this.chapters = [];
       
        this.subtitle = control.content.findName("Subtitles");
        this.subtitleCanvas = control.content.findName("SubtitleCanvas");
        this.subtitleCanvas.visibility = "Collapsed";
      
        this.subtitleOut = control.content.findName("SubOut");
        this.subtitleIn = control.content.findName("SubIn");
        this.supringCanvas = control.content.findName("SupringCanvas");
        this.supring = control.content.findName("Supring");
        this.supringOut = control.content.findName("SupringOut");
        this.supringIn = control.content.findName("SupringIn");
        this.alertOut = control.content.findName("AlertOut");
        this.alertIn = control.content.findName("AlertIn");
        this.chapterTxt = control.content.findName("Chapter");
        this.chapterTxt.visibility = "Collapsed";
        this.infoTxt = control.content.findName("infoTxt");
        this.infoTxt.visibility = "collapsed";
        this.btnControl = control.content.findName("BtmControls");
        
        if (this.playerControlBar == false) {
            this.btnControl.Visibility = "Collapsed"
        }
        
        this.btnControlsIn = control.content.findName("btmControlsIn");
        this.btnControlsOut = control.content.findName("btmControlsOut");
        this.plugin.content.OnFullScreenChange = Function.createDelegate(this, this.onFullScreenChanged);
        
        //BUFFERING AND DOWNLOAD
        //this.MediaPlayer.addEventListener("downloadProgressChanged", this._handleDownloadProgress);
        //this.MediaPlayer.addEventListener("bufferingProgressChanged", this._handleBufferProgress);
        this.isTopOn = false;
        this.top = control.content.findName("TopCanvas");
        
        if (this.playerTitleBar == true) {
            this.top.Visibility = "Visible"
            this.isTopOn = true;
        }
        this.subTimeOut;
        this.supTimeOut;
        this.setURL(this.mediaURL);
   },
   
   onClientMediaOpened: function(sender, eventArgs) {},
   onClientMediaEnded: function(sender, eventArgs) {},
   onClientChapterStarted: function(sender, eventArgs) {},
   onClientChapterReached: function(sender, eventArgs) {},
   onClientMediaFailed: function(sender, eventArgs) {},
   onClientVolumeChanged: function(sender, eventArgs) {},
   onClientFullScreen: function(sender, eventArgs) {},
   onClientStateChanged: function(sender, eventArgs) {},
     
   _onStateChanged: function(sender, args) {
       if (this._player.get_playState() == "Buffering" || this._player.get_playState() == "Stopped") {
            this._clearScreen();
       }
       this.onClientStateChanged(sender, args);
   },
   
   _onChapterStarted: function(sender, args) {
        this.onClientChapterStarted(sender, args);
   },
   
   _onVolumeChanged: function(sender, args) {
        this.onClientVolumeChanged(sender, args);
   },
   
   onFullScreenChanged: function(sender, args) {
        var plugin = sender.getHost();
        GLOBAL_screen = plugin.content.fullScreen;
        this._updateLayout(plugin.content.actualWidth, plugin.content.actualHeight);
    },
    
    _updateLayout: function(width, height) {
        var w = width;
        var h = height;
        var controller_bg = this.plugin.content.findName("bar_bg");
        var controller_xpos = "0";
        var controller_ypos = "309.001";
        var seperators = this.plugin.content.findName("SeperatorCanvas");
        var lines = this.plugin.content.findName("linesCanvas");
        var buffTxt = this.plugin.content.findName("BufferingText");
        var buffArea = this.plugin.content.findName("BufferingArea");
        var volumBg = this.plugin.content.findName("VolumeBg");
        var volumOutline = this.plugin.content.findName("outlineCanvas");
        if (GLOBAL_screen) {
            if (this.isTopOn == true) {
                this.top.Visibility = "collapsed"
                this.isTopOn = true;
            }
            this.subtitleCanvas.visibility = "collapsed";
            this.supringCanvas.visibility = "collapsed";
            this.btnControl["canvas.top"] = (h - this.btnControl["height"]) - 50;
            this.btnControl["canvas.left"] = (w - this.btnControl["width"])/2;
            controller_bg["fill"] = "#FF000000";
            controller_bg.Opacity = 0.5;
            seperators.visibility = "collapsed";
            lines.visibility = "collapsed";
            volumBg["fill"] = "#FF000000";
            volumOutline.opacity = 0;
            this.MediaPlayer.width = w;
            this.MediaPlayer.height = h;
        } else {
            if (this.isTopOn == true) {
                this.top.Visibility = "Visible"
                this.isTopOn = true;
            }
            this.subtitleCanvas.visibility = "visible";
            this.supringCanvas.visibility = "visible";
            this.btnControl["canvas.top"] = 288;
            this.btnControl["canvas.left"] = controller_xpos;
            this.btnControl.Opacity = 1;
            controller_bg["fill"] = "#FFECE7D1";
            controller_bg.Opacity = 1;
            seperators.visibility = "visible";
            lines.visibility = "visible";
            volumBg["fill"] = "#FFECE7D1";
            volumOutline.opacity = 1;
            this.MediaPlayer.width = w;
            this.MediaPlayer.height = 288;
        }
        buffTxt["canvas.top"] = (h - buffTxt["height"]) /2;
        buffTxt["canvas.left"] = ((w - buffTxt["width"])/2) + 5;
        buffArea["canvas.top"] = (h - buffArea["height"]) /2;
        buffArea["canvas.left"] = (w - buffArea["width"])/2;
        this.onClientFullScreen();
    },
  
    _onMediaOpened: function(sender, eventArgs) {
       //CHAPTERS
       this.chapters.length = 0;
            
       var isLive = mediaElements[this._currentMediainfo].broadcast;
       
       if (!this.MediaPlayer.CanPause) {
            //this._player._canSeek = false;
            //this._stop();
            //this._play();
       } else { // if (isLive == "odm") {
          //SUBTITLES
         
          var media_chapters = mediaElements[this._currentMediainfo].getChapters();
          var len = media_chapters.length;
          
          var indextime = parseInt(mediaElements[this._currentMediainfo].timeindex);
          if (indextime > 0) {
            this.seekTo(indextime);
          }
          
          for (var i = 0 ; i < media_chapters.length ; i++) {
            var ch_title = media_chapters[i].ch_title;
            var ch_time = fixTime(parseInt(media_chapters[i].ch_time));
            var img = media_chapters[i].img;
            
            var ch_xaml = '<TimelineMarker Time="' + ch_time + '" Type="Chapter" Text="' + ch_title.replace(/"/g,'') + '" />';
            
	    var ch_marker = this.MediaPlayer.getHost().content.createFromXaml(ch_xaml);
            this.MediaPlayer.markers.add(ch_marker);

          } 
          
          this.subtitle.Text = "";
          this.supring.Text = "";
          loadSubtitle(mediaElements[this._currentMediainfo].subURL);
       }
       //this.infoTxt.visibility = "visible";
       //this.infoTxt.Text = "CanSeek: "+this._player._canSeek+" > CanPause: "+this.MediaPlayer.CanPause;
             
       this.onClientMediaOpened();
       
    },
    
    _onMarkerReached: function(sender, eventArgs) { //oversteer event from player.js
        //window.status = "marker: "+eventArgs._marker.type+": "+eventArgs._marker.text;
        if (eventArgs._marker.type == 'Subtitle') {
            if (this.subtitleCanvas.visibility == "Collapsed" && GLOBAL_plugin.content.fullScreen == false) {
                this.subtitleCanvas.visibility = "visible";
                this.subtitleCanvas.opacity = 0;
            }
            var sub_ani = this.plugin.content.findName("SubIn");
            if (this.subtitleCanvas.Opacity == 0) {
                sub_ani.begin();
                this.subTimeOut = setTimeout(Function.createDelegate(this, this._subtitlesOut), 10000);
            } else {
            
            }
            this.subtitle.Text = eventArgs._marker.text;
        } 
        
        if (eventArgs._marker.type == 'Supring') {
            
            if (this.isTopOn == true) {
                this.supringCanvas["canvas.top"] = this.top["height"]+3;
            } else {
                this.supringCanvas["canvas.top"] = 3;
            }
            if (this.supringCanvas.Opacity == 0) {
                this.supringIn.begin();
            }
            clearTimeout(this.supTimeOut);
            this.supTimeOut = setTimeout(Function.createDelegate(this, this._supringOut), 5000);
            this.supring.Text = eventArgs._marker.text;
        } 
        
        if (eventArgs._marker.type == 'Chapter') {
            this.onClientChapterReached();
        }
    },
    
    _subtitlesOut: function() {
        clearTimeout(this.subTimeOut);
        this.subtitleOut.begin();
    },
    
    _supringOut: function(sender) {
         clearTimeout(this.supTimeOut);
         this.supringOut.begin();
    },
    
    _onMediaEnded: function(sender, eventArgs) {
        this.onClientMediaEnded(sender, eventArgs);
        window.setTimeout( Function.createDelegate(this, this.playNextVideo), 1000);
    },
    
    _onMediaFailed: function(sender, eventArgs) {
        this.onClientMediaFailed(sender, eventArgs);
        //alert(String.format( Ee.UI.Xaml.Media.Res.mediaFailed, this._player.get_mediaUrl() ) );
    },
    playNextVideo: function() {
        this._getMedia("next");
    },
    
    playPrevVideo: function() { 
       this._getMedia("prev");
    },
    
    _theMediaInfo: function(nr) {
        var chapterArr = [];
        var media_chapters = mediaElements[nr].getChapters();
        var len = media_chapters.length;
        
        for (var i = 0 ; i < media_chapters.length ; i++) {
           var ch_title = media_chapters[i].ch_title;
           var ch_time = parseInt(media_chapters[i].ch_time);
           var img = media_chapters[i].img;
           chapterArr.push({time: ch_time, Type: "Chapter ", text: ch_title});
        }
        
        
         
        return { 
            "mediaUrl": mediaElements[nr].medieURL,
            "placeholderImage": "",
            "chapters": chapterArr
            };
         
    },
    
    _getMedia: function( direction ) {
        this._clearScreen(true);
        
        var curNr;
        if (direction == "next") {
            this._currentMediainfo++;
         } else if (direction == "prev") {
            this._currentMediainfo--;
         } else {
            //error
         }
         curNr = this._currentMediainfo;
         var mediaLen = (mediaElements.length) - 1;
         //alert("curnr: "+curNr+" | media len: "+mediaLen);
         if (curNr <= mediaLen) { //&& curNr > -1
            this._player.set_mediainfo( this._theMediaInfo(curNr) );
         } else {
             this.MediaPlayer.Pause();
            //this._player.set_mediainfo({mediaUrl:null});
            //this._clearScreen(true); //true
            //this.MediaPlayer.stop();
            //alert("no more files");
         }
    },
    
    _clearScreen: function(state) {
        if (state == true) {
            //this._player._mediaEnded = true;
            this.MediaPlayer.Pause();
            //this.MediaPlayer.Stop();
            //this.seekTo(0);
        }
        this.subtitle.Text = "";
        this.subtitleCanvas.opacity = 0;
        this.supring.Text = "";
        this.supringCanvas.Opacity = 0;
    },
    
    onTimeSliderChanged: function () {
        this._clearScreen();
    }, 
    
    setTop: function(state) {
        if (state == true) {
            this.top.Visibility = "Visible";
            this.isTopOn = state;
        } else {
            this.top.Visibility = "Collapsed";
            this.isTopOn = state;
        }
    },
    
    setURL: function(mediaUrl) {
        mediaElements.length = 0;
        supArray.length = 0;
        subArray.length = 0;
        this._currentMediainfo = -1;
        this._clearScreen();
        loadMainXML(this, this.plugin, mediaUrl, this.MediaPlayer);
        
    },
    
    nextChapter: function() {
        this.currentChapter++;
        this._player._chapterNext();
    },
    
    prevChapter: function() {
       this.currentChapter--;
       this._player._chapterPrevious();
    }, 
        
    _stop: function() {
        this._player.stop();
    },
    
    _pause: function() {
        this._player.pause();
    },
    
    _play: function() {
        this._player.play();
    },
   
    setVolumeUp: function() {
        var vol = this._player.volume;
        vol+= 0.1;
        if (vol <= 1) {
            this._player.set_volume(vol);
        }
    }, 
    
    setVolumeDown: function() {
        var vol = this._player.volume;
        vol-= 0.1;
        if (vol >= 0) {
            this._player.set_volume(vol);
        }
    },
    
    mute: function() {
        this._player.toggleMuted();
    }, 
    
    seekTo: function(pos) {
        this._player.set_timeIndex(pos);
    }
}

